﻿using System;
using System.Linq;
using WebBotDetector.WebModule;

namespace BotDetector.Core.WebModule
{
    public class WebTest : DetectorAuxiliaryModule
    {
        private const double BOT_CHANCE_WHEN_GOOGLE_AND_BING_SEARCH_POSITIVE = 1;
        private const double BOT_CHANCE_WHEN_GOOGLE_SEARCH_POSITIVE = 0.8;
        private const double BOT_CHANCE_WHEN_BING_SEARCH_POSITIVE = 0.7;
        private const double BOT_CHANCE_WHEN_NO_SEARCH_POSITIVE = 0;
        private const double BEGINING_WORDS = 5;

        private WebSearchUtility webUtility;

        public WebTest()
        {
            webUtility = new WebSearchUtility();
        }

        public double TestForBot(string text)
        {
            string textBegining = GetTextBegining(text);

            bool googleResultPercentage = GoogleTestBot(textBegining);
            bool bingResultPercentage = BingTestBot(textBegining);

            return GetBotPercentage(googleResultPercentage, bingResultPercentage);
        }

        private string GetTextBegining(string text)
        {
            string[] words = text.Split(' ');
            string queryText = "";

            int wordCount = words.Count();
            if (wordCount > 1)
            {
                int x = 0;
                while (x < BEGINING_WORDS && x < wordCount)
                {
                    queryText += words[x];
                    queryText += " ";
                    x++;
                }
            }
            else
            {
                queryText = words[0];
            }
            return queryText;
        }

        private double GetBotPercentage(bool googleResult, bool bingResult)
        {
            if (googleResult && bingResult)
                return BOT_CHANCE_WHEN_GOOGLE_AND_BING_SEARCH_POSITIVE;
            else if (googleResult)
                return BOT_CHANCE_WHEN_GOOGLE_SEARCH_POSITIVE;
            else if (bingResult)
                return BOT_CHANCE_WHEN_BING_SEARCH_POSITIVE;
            else return BOT_CHANCE_WHEN_NO_SEARCH_POSITIVE;
        }

        private bool GoogleTestBot(string text)
        {
            long googleTotalResults = webUtility.GetGoogleTotalResults(text, false);

            if (googleTotalResults >= 10)
                return false;

            return true;
        }

        private bool BingTestBot(string text)
        {
            long bingTotalResults = webUtility.GetBingTotalResults(text, false);

            if (bingTotalResults >= 10)
                return false;

            return true;
        
        }
    }
}
